import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { NavController, NavParams, ToastController } from 'ionic-angular';
import { UserItemPage } from '../userItem/userItem';

@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {
  group: FormGroup;

  timer = 120;
  timerTick: any;

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    private builder: FormBuilder,
    private toastCtrl: ToastController,
    private translate: TranslateService,
    private rest: RestService) {
    this.group = this.builder.group({
      username: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(16), Validators.pattern('[\+0-9]+')]],
      vcode: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(4), Validators.pattern('[0-9]+')]],
      password: ['', [Validators.required]],
      checkbox: ['false', [Validators.requiredTrue]]
    });
  }

  clearUsername() {
    this.group.controls.username.setValue('');
  }

  nav2Item() {
    this.navCtrl.push(UserItemPage, {
    });
  }

doSignup() {
  this.rest.post('/api/keycloak/register', {
    phoneNumber: this.group.controls.username.value,
    code: this.group.controls.vcode.value,
    password: this.group.controls.password.value
  }).subscribe(resp => {
    if (resp.status >= 200 && resp.status < 300) {
      this.rest.saveUser({
        username: this.group.controls.username.value,
        password: this.group.controls.password.value,
        locale: '',
        role: ''
      });
      this.navCtrl.pop();
    } else {
      if (resp.status === 409) {
        this.showToast(this.translate.get('userExists')['value']);
      } else if (resp.status === 406) {
        this.showToast(this.translate.get('codeMismatch')['value']);
      } else {
        this.showToast(this.translate.get('badRequest')['value']);
      }
    }
  }, error => {
    this.showToast(this.translate.get('badRequest')['value']);
    console.error('Failed to register user!');
  });
}

showToast(message) {
  const toast = this.toastCtrl.create({
    message: message,
    duration: 5000,
    position: 'bottom'
  });

  toast.present(toast);
}

getVerificationCode() {
  if (this.timer !== 120) {
    return;
  }

  this.startTick();

  this.rest.getValidateCode(this.group.controls.username.value).subscribe(resp => {
    if (resp.status !== 200) {
      console.error('Failed to get code: ' + resp.info);
      if (resp.info) {
        this.showToast(resp.info);
      }
      this.stopTick();
    }
  }, error => {
    console.error('Failed to get code' + error);
    this.showToast(this.translate.get('badRequest')['value']);
    this.stopTick();
  });
}

getCodeText() {
  if (this.timer === 120) {
    return this.translate.get('getCode')['value'];
  } else {
    return this.timer + this.translate.get('waitCode')['value'];
  }
}

stopTick() {
  if (this.timerTick) {
    clearInterval(this.timerTick);
    this.timer = 120;
  } else {
    this.timer = 120;
  }
}

startTick() {
  this.timer = 99;

  this.timerTick = setInterval(() => {
    if (this.timer <= 1) {
      this.timer = 120;
      if (this.timerTick) {
        clearInterval(this.timerTick);
      }
    } else {
      this.timer--;
    }
  }, 1000);
}

navBack() {
  this.navCtrl.pop();
}

ionViewDidLoad() {
}
}
